package com.controller;

import com.model.Result;
import com.model.Role;
import com.service.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/8/31.
 */
@Controller
public class RoleController {
    @Resource
    private RoleService roleService;

    @RequestMapping("getRoleList.do")
    public String getRoleList(@RequestParam(value = "name",required = false)String name,
                              HttpServletRequest request){
        List<Role> roles = roleService.getRoleList(new Role(name));
        request.setAttribute("roles",roles);
        request.setAttribute("name",name);
        return "role";
    }

    @RequestMapping("insertRole.do")
    public String insertRole(Role role, HttpSession session, HttpServletRequest request){
        String manager = (String) session.getAttribute("sessionUsername");
        if(manager == null){
            return "login";
        }
        String creator = manager;
        Date date = new Date();
        Long createTime = date.getTime()/1000;
        role.setCreatetime(createTime);
        role.setCreator(creator);
        int result = roleService.createRole(role);
        if(result==0){
            request.setAttribute("error","添加失败");
        }
        return getRoleList(null,request);
    }

    @RequestMapping("modifyRole.do")
    public String modifyRole(Role role, HttpServletRequest request){
        int result = roleService.modifyRole(role);
        if(result==0){
            request.setAttribute("error","修改失败");
        }
        return getRoleList(null,request);
    }

    @RequestMapping("changeRoleStatus")
    public String changeRoleStatus(@RequestParam("id")Integer id,
                                   @RequestParam("status")Integer status,
                                   HttpServletRequest request){
        int result = roleService.changeStatus(new Role(id,status));
        if(result==0){
            request.setAttribute("error","修改失败");
        }
        return getRoleList(null,request);
    }

    @RequestMapping("deleteRole.do")
    public String deleteRole(@RequestParam("id")Integer id,
                             HttpServletRequest request){
        int result = roleService.deleteRole(new Role(id));
        if(result==0){
            request.setAttribute("error","删除失败");
        }
        return getRoleList(null,request);
    }

    @RequestMapping("checkRoleNameExist")
    @ResponseBody
    public Result checkRoleNameExist(@RequestParam("name")String name){
        int count = roleService.checkExist(new Role(name));
        return new Result(count,null,null);
    }

}
